
package com.gamatechno.solodestinationnew;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.gamatechno.solodestinationnew.adapter.CustomAdapter;
import com.gamatechno.solodestinationnew.animation.SlidingUpPanelLayout;
import com.gamatechno.solodestinationnew.entity.E_Event;
import com.gamatechno.solodestinationnew.helper.JSONHelper;
import com.gamatechno.solodestinationnew.utils.Utils;
import com.gamatechno.solodestinationnew.utils.Webservice;
import com.roomorama.caldroid.CaldroidFragment;
import com.roomorama.caldroid.CaldroidListener;

public class EventActivity extends BaseActivity {

    // private boolean undo = false;
    private CaldroidFragment caldroidFragment;
    // private CaldroidFragment doalogCaldroidFragment;
    private static final String TAG = "EVENT";
    private static final String TAG_STARTDATE = "startDate";
    private static final String TAG_NAME = "name";
    private String URL;
    List<E_Event> dataList;
    ListAdapter adapter;
    ListView eList;
    TextView eText;
    LinearLayout slideHandleButton;
    CaldroidListener listener;

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_event);
        eText = (TextView) findViewById(R.id.noevent);
        eList = (ListView) findViewById(R.id.eventlist);

        // final SimpleDateFormat formatter = new
        // SimpleDateFormat("dd MMM yyyy");

        URL = Webservice.GET_EVENT(Utils.getDataStringFromSP(this,
                Utils.PREF_BAHASA));

        getData(URL);

        // setup sliding
        SlidingUpPanelLayout layout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
        layout.setAnchorPoint(0.3f);
        layout.setEnableDragViewTouchEvents(true);
        layout.setPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {

            @Override
            public void onPanelSlide(View panel, float slideOffset) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onPanelExpanded(View panel) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPanelCollapsed(View panel) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPanelAnchored(View panel) {
                // TODO Auto-generated method stub
            }
        });

        // setup caldroid

        caldroidFragment = new CaldroidFragment();

        // If Activity is created after rotation
        if (savedInstanceState != null) {
            caldroidFragment.restoreStatesFromKey(savedInstanceState,
                    "CALDROID_SAVED_STATE");
        }
        // If activity is created from fresh
        else {
            Bundle args = new Bundle();
            Calendar cal = Calendar.getInstance();
            args.putInt(CaldroidFragment.MONTH, cal.get(Calendar.MONTH) + 1);
            args.putInt(CaldroidFragment.YEAR, cal.get(Calendar.YEAR));
            args.putBoolean(CaldroidFragment.ENABLE_SWIPE, true);
            args.putBoolean(CaldroidFragment.SIX_WEEKS_IN_CALENDAR, true);

            // Uncomment this to customize startDayOfWeek
            // args.putInt(CaldroidFragment.START_DAY_OF_WEEK,
            // CaldroidFragment.TUESDAY); // Tuesday
            caldroidFragment.setArguments(args);
        }

        // Attach to the activity
        FragmentTransaction t = getSupportFragmentManager().beginTransaction();
        t.replace(R.id.calendar1, caldroidFragment);
        t.commit();

        // Setup listener
        listener = new CaldroidListener() {

            @Override
            public void onSelectDate(Date date, View view) {
                // Toast.makeText(getApplicationContext(),
                // formatter.format(date),
                // Toast.LENGTH_SHORT).show();
                String sDate = dateFormat.format(date);
                if (!sDate.isEmpty()) {
                    showEventList(sDate);
                } else {
                    eText.setVisibility(View.VISIBLE);
                    eList.setVisibility(View.GONE);
                }

            }

            @Override
            public void onChangeMonth(int month, int year) {
                eText.setVisibility(View.VISIBLE);
                eList.setVisibility(View.GONE);
            }

            @Override
            public void onLongClickDate(Date date, View view) {
            }

            @Override
            public void onCaldroidViewCreated() {
                if (caldroidFragment.getLeftArrowButton() != null) {
                }
            }

        };

        eList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                TextView tID = (TextView) v.findViewById(R.id.ID);
                String id = tID.getText().toString();
                Log.d("id selected", id);
                if (!id.isEmpty()) {
                    GoToEventDetail(id);
                }

            }
        });

        // Setup Caldroid to Listener
        // caldroidFragment.setCaldroidListener(listener);

    }

    private void getData(String URL) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
                URL, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject obj) {
                        setSupportProgressBarIndeterminateVisibility(false);
                        Utils.TRACE(
                                "EventActivity.getData(...).new Listener() {...}",
                                "onResponse : " + obj.toString());
                        try {
                            if (obj.getInt("status") == 200) {
                                if (obj.getJSONArray("result").length() > 0) {
                                    dataList = JSONHelper.getEvent(obj
                                            .getJSONArray("result"));
                                    setCustomResourceForDates(dataList);

                                    // set listener
                                    caldroidFragment.setCaldroidListener(listener);
                                }
                            }
                            caldroidFragment.refreshView();
                        } catch (JSONException e) {
                            Utils.TRACE("EventActivity",
                                    "getData : " + e.getMessage());
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        setSupportProgressBarIndeterminateVisibility(false);
                        Utils.TRACE(
                                "EventActivity.getData(...).new ErrorListener() {...}",
                                "onErrorResponse : " + error.toString());
                        Utils.showVolleyError(EventActivity.this, error);
                    }
                });
        BaseApplication.getInstance().addToRequestQueue(request, TAG);
        setSupportProgressBarIndeterminateVisibility(true);
    }

    /**
     * set warna merah for event
     * 
     * @param dataList
     */
    private void setCustomResourceForDates(List<E_Event> dataList) {
        Date myDate = null;
        String sToday = dateFormat.format(new Date());
        Date today = null;
        for (int i = 0; i < dataList.size(); i++) {
            try {
                if (caldroidFragment != null) {
                    myDate = dateFormat.parse(dataList.get(i).getStartDate());
                    today = dateFormat.parse(sToday);
                    caldroidFragment.setBackgroundResourceForDate(R.color.red,
                            myDate);
                    if (myDate.equals(today)) {
                        caldroidFragment.setBackgroundResourceForDate(
                                R.drawable.yellow_border_today, today);
                        showEventList(sToday);
                    }

                }
            } catch (Exception e) {
                Utils.TRACE("EventActivity",
                        "setCustomResourceForDates : " + e.getMessage());
            }

        }

    }

    // show today event list

    private void showEventList(String Date) {
        eText.setVisibility(View.GONE);
        eList.setVisibility(View.VISIBLE);

        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();

        for (E_Event e : dataList) {
            if (e.getStartDate().substring(0, 10).equals(Date)) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("ID", String.valueOf(e.getId()));
                String[] data = e.getStartDate().split(" ");
                map.put(TAG_STARTDATE, data[0]);
                map.put(TAG_NAME, e.getName());
                list.add(map);
            }
        }

        adapter = new CustomAdapter(getApplicationContext(), list,
                R.layout.item_list_event, new String[] {
                        "ID", TAG_STARTDATE,
                        TAG_NAME
                },
                new int[] {
                        R.id.ID, R.id.eTgl, R.id.eEvent
                });

        eList.setAdapter(adapter);

    }

    private void GoToEventDetail(String id) {
        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        for (E_Event e : dataList) {
            if (String.valueOf(e.getId()).equals(id)) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("id", String.valueOf(e.getId()));
                map.put("nama", e.getName());
                map.put("startDate", e.getStartDate());
                map.put("endDate", e.getEndDate());
                map.put("category", e.getCategory());
                map.put("description", e.getDescription());
                map.put("image", e.getImages());
                map.put("lat", e.getLat());
                map.put("lon", e.getLon());
                list.add(map);
            }
        }
        Intent i = new Intent(EventActivity.this, EventDetailActivity.class);
        i.putExtra("detail", list);
        startActivity(i);
    }

}
